;(function(window, $) {
  var isAssert = true
  var normal = TianMap.getNormal()
  // var excludeStationList = window.geExcludeStationList
  var VoronoiColor = {
    totalFreq: function(f) {
      // '#b1e1b1', '#8cc88c', '#6caf6c', '#58a158', '#439243', '#307a2f', '#2f7a51'
      var totalFreqColors = [
        ['#b1e1b1', '1'],
        ['#8cc88c', '2'],
        ['#6caf6c', '3'],
        ['#58a158', '4'],
        ['#439243', '5'],
        ['#307a2f', '6'],
        ['#2f7a51', '7']
      ]

      var ele = totalFreqColors[f - 1]

      return ele ? ele[0] : 'rgb(124,205,124)'
    },
    upFlow: function(f) {
      var color = 'rgb(124,205,124)'

      if (f >= 0 && f < 10) {
        color = '#b1e1b1'
      } else if (10 <= f && f < 100) {
        color = '#8cc88c'
      } else if (100 <= f && f < 1000) {
        color = '#6caf6c'
      } else if (1000 <= f && f < 10000) {
        color = '#58a158'
      } else if (10000 <= f && f < 100000) {
        color = '#439243'
      } else if (100000 <= f && f < 1000000) {
        color = '#307a2f'
      } else if (1000000 <= f && f < 10000000) {
        color = '#2f7a51'
      }

      return color
    },
    downFlow: function(f) {
      var color = 'rgb(124,205,124)'

      if (f >= 0 && f < 10) {
        color = '#b1e1b1'
      } else if (10 <= f && f < 100) {
        color = '#8cc88c'
      } else if (100 <= f && f < 1000) {
        color = '#6caf6c'
      } else if (1000 <= f && f < 10000) {
        color = '#58a158'
      } else if (10000 <= f && f < 100000) {
        color = '#439243'
      } else if (100000 <= f && f < 1000000) {
        color = '#307a2f'
      } else if (1000000 <= f && f < 10000000) {
        color = '#2f7a51'
      }

      return color
    },
    totalFlow: function(f) {
      var color = 'rgba(124,205,124, 1)'

      if (f >= 0 && f < 10) {
        color = '#b1e1b1'
      } else if (10 <= f && f < 100) {
        color = '#8cc88c'
      } else if (100 <= f && f < 1000) {
        color = '#6caf6c'
      } else if (1000 <= f && f < 10000) {
        color = '#58a158'
      } else if (10000 <= f && f < 100000) {
        color = '#439243'
      } else if (100000 <= f && f < 1000000) {
        color = '#307a2f'
      } else if (1000000 <= f && f < 10000000) {
        color = '#2f7a51'
      }

      return color
    }
  }

  var Map = {
    init: function() {
      var me = this
      me.render()
      me.bind()
    },
    const: {
      cellZoom: 15, // 300m
      // cellZoom: 6, // 10km
      voronoiZoom: 8, // 50km 大于等于50km时隐藏泰森多边形
      dotLayerZoom: 6, //
      voronoiFillOpacity: 0.5,
      circleMarkerColor: 'yellow'
    },
    data: {
      stationList: [],
      polygons: [],
      cellList: [],
      contentId: 'totalFreq',
      currentZoom: 10,
      // dotLayerShow: false,
      city: ''
    },
    widget: {
      totalFreq: L.control({
        position: 'bottomright'
      }),
      upFlow: L.control({
        position: 'bottomright'
      }),
      downFlow: L.control({
        position: 'bottomright'
      }),
      totalFlow: L.control({
        position: 'bottomright'
      })
    },
    cellWidget: L.control({
      position: 'bottomleft'
    }),
    layer: {
      canvas: L.canvasLayer(),
      // dotLayer: L.featureGroup(),
      voronoiLayer: L.d3SvgOverlay(function(sel, proj) {
        console.assert(isAssert, proj)
        var me = Map
        var polygons = me.data.polygons
        var stationList = me.data.stationList
        var contentId = me.data.contentId
        // var zoom = proj.getZoom();
        // console.assert(isAssert, zoom);

        var upd = sel.selectAll('path').data(polygons)
        var $curPath = undefined

        upd
          .enter()
          .append('path')
          .attr('opacity', function(d, i) {
            // 点如果在边缘位置就填充透明
            return N.Data.isPointInArr(stationList[i])
              ? 0
              : me.const.voronoiFillOpacity
            // return (N.Color.getOpacity(polygons[i]) === 0) ? 'true' : 'false';
          })
          .attr('d', function(d, i) {
            var newPoints = N.Data.resample(polygons[i])
            return d3.svg.line().interpolate('basis-closed')(newPoints)
            // return d3.svg.line().interpolate("basis-closed");
          })
          .attr('stroke-opacity', function(d, i) {
            // return stationList[i].f >= 8 ? 0.8 : 0.3;
            return 0.8
          })
          .attr('stroke-width', function() {
            return 0.3;

            // 无法动态设置strokeWidth
            // if (zoom >= 13) {
            //   return 0.01;
            // } else {
            //   return 0.5;
            // }
            
          })
          .attr('stroke', function() {
            return 'rgb(255,102,1)';
          })
          // .attr('point', function (d, i) {
          //   if (d && d.hasOwnProperty('point')) {
          //     return d.point[0] + ',' + d.point[1];
          //   }

          //   return;
          // })
          // .attr('style', 'pointer-events:visiblePainted;')
          .style('fill', function(d, i) {
            // return N.Color.getVoronoiColor(stationList[i].f, legendList);

            return VoronoiColor[contentId](stationList[i].f)
            // return 'rgba(124,205,124, 1)';
          })
          // .on('click', function(d, i) {
          //   console.log(stationList[i])
          //   if ($curPath) {
          //     $curPath.css('fill', $curPath.attr('data-color'))
          //   }

          //   $curPath = $(upd[0][i])

          //   $curPath.attr('data-color', $curPath.css('fill'))
          //   $curPath.css('fill', 'red')
          // })
      }, {
        zoomHide: true,
        zoomDraw: true
      }),
      normal: normal,
      overlay: {},
      baseLayer: {
        // 切换基础图层的对象
        地图: normal,
        影像: TianMap.getImage(),
        地形: TianMap.getTerrain()
      }
    },
    render: function() {
      var me = this

      me.cmap = N.map('map', me.layer.normal) // 封装的leaflet地图方法
      me.cmap
        .addZoom()
        .addCoord()
        .addScale()
        .setLayers(me.layer.baseLayer, me.layer.overlay)
      ;(me.map = me.cmap.getLmap()), // leaflet map 对象实例
        me.map.setView(
          {
            lng: 107.9,
            lat: 35.84
          },
          4
        )
    },
    bind: function() {
      var me = this
      var map = me.map
      var widget = me.widget

      // 拖动事件
      map.on('dragstart', $.proxy(me['_do_dragstart'], this))
      // 拖动结束事件
      map.on('dragend', $.proxy(me['_do_dragend'], this))
      map.on('zoomstart', $.proxy(me['_do_zoomstart'], this))
      map.on('zoom', $.proxy(me['_do_zoom'], this))
      map.on('zoomend', $.proxy(me['_do_zoomend'], this))

      widget.totalFreq.onAdd = $.proxy(me['_addwidget_totalfreq'], this)
      widget.upFlow.onAdd = $.proxy(me['_addwidget_upflow'], this)
      widget.downFlow.onAdd = $.proxy(me['_addwidget_downflow'], this)
      widget.totalFlow.onAdd = $.proxy(me['_addwidget_totalflow'], this)
      me.cellWidget.onAdd = $.proxy(me['_addwidget_cellfreq'], this)
    },
    _addwidget_cellfreq: function(e) {
      var div = L.DomUtil.create('div', 'map-freqlegend')

      // A: 'rgb(0, 160, 0)', 'rgb(0, 180, 0)', 'rgb(0, 222, 0)', 'rgb(0, 255, 0)'
      // F: ['rgb(235, 100, 0)', 'rgb(240, 80, 0)', 'rgb(240, 60, 0)', 'rgb(240, 40, 0)'],
      // D: ['rgb(185, 185, 0)', 'rgb(205, 205, 0)', 'rgb(225, 225, 0)', 'rgb(245, 245, 0)'],
      // 'FDD-900': ['rgb(0, 200, 200)', 'rgb(0, 160, 240)', 'rgb(0, 160, 240)', 'rgb(0, 0, 255)'],
      // 'FDD-1800': ['rgb(235, 140, 235)', 'rgb(235, 120, 235)', 'rgb(235, 80, 235)', 'rgb(255, 0, 255)'],
      // E: ['rgb(254, 154, 132)', 'rgb(254, 100, 132)', 'rgb(254, 70, 110)', 'rgb(254, 12, 63)']

      var cellFreqColors = [
        ['rgb(0, 255, 0)', 'A'],
        // ['rgb(0, 222, 0)', 'A'],
        // ['rgb(0, 180, 0)', 'A'],
        // ['rgb(0, 160, 0)', 'A'],
        ['rgb(235, 100, 0)', 'F'],
        // ['rgb(240, 80, 0)', 'F'],
        // ['rgb(240, 60, 0)', 'F'],
        // ['rgb(240, 40, 0)', 'F'],
        ['rgb(185, 185, 0)', 'D'],
        // ['rgb(205, 205, 0)', 'D'],
        // ['rgb(225, 225, 0)', 'D'],
        // ['rgb(245, 245, 0)', 'D'],
        ['rgb(0, 200, 200)', 'FDD-900'],
        // ['rgb(0, 160, 240)', 'FDD-900'],
        // ['rgb(0, 120, 240)', 'FDD-900'],
        // ['rgb(0, 0, 255)', 'FDD-900'],
        ['rgb(235, 140, 235)', 'FDD-1800'],
        // ['rgb(235, 120, 235)', 'FDD-1800'],
        // ['rgb(235, 80, 235)', 'FDD-1800'],
        // ['rgb(255, 0, 255)', 'FDD-1800'],
        ['rgb(192,192,192)', 'E']
      ]

      div.innerHTML = N.Dom.getColorLegend(cellFreqColors)

      return div
    },
    _addwidget_totalfreq: function(e) {
      var me = this
      var div = L.DomUtil.create('div', 'map-freqlegend')
      // '#b1e1b1', '#8cc88c', '#6caf6c', '#58a158', '#439243', '#307a2f', '#2f7a51'
      var totalFreqColors = [
        ['rgba(177, 225, 177, ' + me.const.voronoiFillOpacity + ')', '1'],
        ['rgba(140, 200, 140, ' + me.const.voronoiFillOpacity + ')', '2'],
        ['rgba(108, 175, 108, ' + me.const.voronoiFillOpacity + ')', '3'],
        ['rgba(88, 161, 88, ' + me.const.voronoiFillOpacity + ')', '4'],
        ['rgba(67, 146, 67, ' + me.const.voronoiFillOpacity + ')', '5'],
        ['rgba(48, 122, 47, ' + me.const.voronoiFillOpacity + ')', '6'],
        ['rgba(47, 122, 81, ' + me.const.voronoiFillOpacity + ')', '7']
      ]

      div.innerHTML = N.Dom.getColorLegend(totalFreqColors)

      return div
    },
    _addwidget_upflow: function(e) {
      var me = this
      var div = L.DomUtil.create('div', 'map-flowlegend')
      var colors = [
        ['rgba(177, 225, 177, ' + me.const.voronoiFillOpacity + ')', '0-10'],
        ['rgba(140, 200, 140, ' + me.const.voronoiFillOpacity + ')', '10-100'],
        [
          'rgba(108, 175, 108, ' + me.const.voronoiFillOpacity + ')',
          '100-1000'
        ],
        [
          'rgba(88, 161, 88, ' + me.const.voronoiFillOpacity + ')',
          '1000-10000'
        ],
        ['rgba(67, 146, 67, ' + me.const.voronoiFillOpacity + ')', '1万-10万'],
        [
          'rgba(48, 122, 47, ' + me.const.voronoiFillOpacity + ')',
          '10万-100万'
        ],
        [
          'rgba(47, 122, 81, ' + me.const.voronoiFillOpacity + ')',
          '100万-1000万'
        ]
      ]

      div.innerHTML = N.Dom.getColorLegend(colors)

      return div
    },
    _addwidget_downflow: function(e) {
      var me = this
      var div = L.DomUtil.create('div', 'map-flowlegend')
      var colors = [
        ['rgba(177, 225, 177, ' + me.const.voronoiFillOpacity + ')', '0-10'],
        ['rgba(140, 200, 140, ' + me.const.voronoiFillOpacity + ')', '10-100'],
        [
          'rgba(108, 175, 108, ' + me.const.voronoiFillOpacity + ')',
          '100-1000'
        ],
        [
          'rgba(88, 161, 88, ' + me.const.voronoiFillOpacity + ')',
          '1000-10000'
        ],
        ['rgba(67, 146, 67, ' + me.const.voronoiFillOpacity + ')', '1万-10万'],
        [
          'rgba(48, 122, 47, ' + me.const.voronoiFillOpacity + ')',
          '10万-100万'
        ],
        [
          'rgba(47, 122, 81, ' + me.const.voronoiFillOpacity + ')',
          '100万-1000万'
        ]
      ]

      div.innerHTML = N.Dom.getColorLegend(colors)

      return div
    },
    _addwidget_totalflow: function(e) {
      var me = this
      var div = L.DomUtil.create('div', 'map-flowlegend')
      var colors = [
        ['rgba(177, 225, 177, ' + me.const.voronoiFillOpacity + ')', '0-10'],
        ['rgba(140, 200, 140, ' + me.const.voronoiFillOpacity + ')', '10-100'],
        [
          'rgba(108, 175, 108, ' + me.const.voronoiFillOpacity + ')',
          '100-1000'
        ],
        [
          'rgba(88, 161, 88, ' + me.const.voronoiFillOpacity + ')',
          '1000-10000'
        ],
        ['rgba(67, 146, 67, ' + me.const.voronoiFillOpacity + ')', '1万-10万'],
        [
          'rgba(48, 122, 47, ' + me.const.voronoiFillOpacity + ')',
          '10万-100万'
        ],
        [
          'rgba(47, 122, 81, ' + me.const.voronoiFillOpacity + ')',
          '100万-1000万'
        ]
      ]

      div.innerHTML = N.Dom.getColorLegend(colors)

      return div
    },
    _do_zoom: function(e) {
      var me = this
      var map = me.map
      var zoom = map.getZoom()
      // console.log('地图缩放级别: ' + zoom)
      me.data.currentZoom = zoom
      var canvas = me.layer.canvas
      // var dotLayer = me.layer.dotLayer
      if (map.hasLayer(canvas)) {
        canvas.delegate(window).removeFrom(map)
      }

      // if (map.hasLayer(dotLayer)) {
      //   dotLayer.removeFrom(map)
      // }
    },
    _do_zoomstart: function(e) {
      var me = this
      var map = me.map
      var canvas = me.layer.canvas
      // var dotLayer = me.layer.dotLayer
      if (map.hasLayer(canvas)) {
        canvas.delegate(window).removeFrom(map)
      }

      // if (map.hasLayer(dotLayer)) {
      //   dotLayer.removeFrom(map)
      // }
    },
    _do_zoomend: function(e) {
      var me = this
      var map = me.map
      var zoom = map.getZoom()
      var canvas = me.layer.canvas
      var voronoiLayer = me.layer.voronoiLayer
      // var dotLayer = me.layer.dotLayer

      // if (zoom >= me.const.cellZoom && me.data.contentId === 'totalFreq') {
      if (me.data.contentId === 'totalFreq') {
        if (!map.hasLayer(canvas)) {
          canvas.delegate(window).addTo(map)
        }
      } else {
        canvas.delegate(window).removeFrom(map)
      }

      if (zoom > me.const.voronoiZoom) {
        if (!map.hasLayer(voronoiLayer)) {
          this.setVoronoiDataSimple(me.data.stationList)
        }
      } else {
        voronoiLayer.removeFrom(map)
      }

      // if (zoom <= me.const.voronoiZoom) {
      //   if (!map.hasLayer(dotLayer)) {
      //     dotLayer.addTo(map)
      //   }
      // } else {
      //   dotLayer.removeFrom(map)
      // }
    },
    _do_dragstart: function(e) {
      var me = this
      var map = me.map
      var canvas = me.layer.canvas
      if (map.hasLayer(canvas)) {
        canvas.delegate(window).removeFrom(map)
      }
    },
    _do_dragend: function(e) {
      var me = this
      var map = me.map
      var zoom = map.getZoom()
      var canvas = me.layer.canvas
      // if (
      //   !map.hasLayer(canvas) &&
      //   zoom >= me.const.cellZoom &&
      //   me.data.contentId === 'totalFreq'
      // ) {
      if (
        !map.hasLayer(canvas) &&
        me.data.contentId === 'totalFreq'
      ) {
        canvas.delegate(window).addTo(map)
      }
    },
    setVoronoiDataSimple: function(stationList) {
      var me = this
      var map = me.map
      var voronoiLayer = me.layer.voronoiLayer
      var layerPoints = stationList.map(function(item) {
        var point = map.latLngToLayerPoint([
          item.lat.toFixed(5),
          item.lon.toFixed(5)
        ])

        return [point.x, point.y]
      })
      me.data.polygons = d3.geom.voronoi(layerPoints)
      voronoiLayer.removeFrom(map)

      if (map.getZoom() > me.const.voronoiZoom) {
        voronoiLayer.addTo(map)
      }
    },
    setVoronoiData: function(stationList, contentId, city, fake) {
      // console.log('stationList', stationList, stationList.length);
      var me = this
      var map = me.map

      var widget = me.widget
      var voronoiLayer = me.layer.voronoiLayer
      // var dotLayer = me.layer.dotLayer

      me.data.city = city
      me.data.contentId = contentId
      if (!fake) {
        var layerPoints = stationList.map(function(item) {
          // var circleMarker = L.circleMarker([item.lat, item.lon], {
          //   radius: 0.2,
          //   color: me.const.circleMarkerColor,
          //   fill: true
          // })
  
          // dotLayer.addLayer(circleMarker)
          var point = map.latLngToLayerPoint([
            item.lat.toFixed(5),
            item.lon.toFixed(5)
          ])
  
          return [point.x, point.y]
        })
      } else {
        var layerPoints = stationList.map(function(item) {
          // var circleMarker = L.circleMarker([item.lat, item.lon], {
          //   radius: 0.2,
          //   color: me.const.circleMarkerColor,
          //   fill: true
          // })
  
          // dotLayer.addLayer(circleMarker)
          var point = map.latLngToLayerPoint([
            item.lat.toFixed(5),
            item.lon.toFixed(5)
          ])
  
          return [point.x, point.y]
        })
      }

      // console.log('layerPoints', layerPoints, layerPoints.length)
      // console.log('layerPoints json', JSON.stringify(layerPoints))

      // if (!map.hasLayer(voronoiLayer)) {
      // var center = N.Data.getCenter(stationList);
      var center = N.Data.getCenterByGuangdongCity(city)
      me.data.stationList = stationList
      me.data.polygons = d3.geom.voronoi(layerPoints)
      // console.log('polygons', me.data.polygons, me.data.polygons.length)
      // console.log('polygons json', JSON.stringify(me.data.polygons))
      voronoiLayer.removeFrom(map)

      widget[contentId].addTo(map)
      map.setView(
        {
          lat: center.lat,
          lng: center.lng
        },
        me.data.currentZoom
      )

      if (map.getZoom() > me.const.voronoiZoom) {
        voronoiLayer.addTo(map)
      }
      // else if (!fake && map.getZoom() > me.const.dotLayerZoom) {
      //   if (!me.data.dotLayerShow) {
      //     dotLayer.addTo(map)
      //     me.data.dotLayerShow = true
      //   }
      // }
    },
    setVoronoiNoData: function() {
      var me = this
      var map = me.map
      me.data.polygons = []
      me.data.stationList = []
      me.layer.voronoiLayer.removeFrom(map)
    },
    setCellData: function(data, city) {
      var me = this
      var map = me.map
      var length = data.length
      var zoom = map.getZoom()
      me.cellWidget.addTo(map)

      if (length === 0) {
        me.setCellNoData()
      } else {
        me.data.cellList = data

        if (zoom >= me.const.cellZoom) {
          me.layer.canvas.delegate(window).addTo(map)
        }
      }
    },
    setCellNoData: function() {
      var me = this
      me.data.cellList = []
      me.layer.canvas.delegate(window).removeFrom(me.map)
    }
  }

  Map.init()
  window.Map = Map
})(window, jQuery)

var fillStyleMap = {
  a0: 'rgb(0, 160, 0)',
  a1: 'rgb(0, 180, 0)',
  a2: 'rgb(0, 222, 0)',
  a3: 'rgb(0, 255, 0)',
  f0: 'rgb(235, 100, 0)',
  f1: 'rgb(240, 80, 0)',
  f2: 'rgb(240, 60, 0)',
  f3: 'rgb(240, 40, 0)',
  d0: 'rgb(185, 185, 0)',
  d1: 'rgb(205, 205, 0)',
  d2: 'rgb(225, 225, 0)',
  d3: 'rgb(245, 245, 0)',
  fdd9000: 'rgb(0, 200, 200)',
  fdd9001: 'rgb(0, 160, 240)',
  fdd9002: 'rgb(0, 120, 240)',
  fdd9003:  'rgb(0, 0, 255)',
  fdd18000: 'rgb(235, 140, 235)',
  fdd18001:  'rgb(235, 120, 235)',
  fdd18002:  'rgb(235, 80, 235)',
  fdd18003:  'rgb(255, 0, 255)',
  e0: 'rgb(192,192,192)',
  e1: 'rgb(160,160,160)',
  e2: 'rgb(130,130,130)',
  e3: 'rgb(100,100,100)'
}

var imgCircle = document.getElementById('circle');

/**
 * gLayers.Leaflet插件的回调函数
 *
 * @param info
 * @return
 */
var onDrawLayer = function(info) {
  'use strict'

  // 地图和createjs的stage
  var map = info.layer._map,
    zoom = map.getZoom(),
    stage = new createjs.Stage(info.canvas)

  stage.enableMouseOver(20)
  stage.clear()

  // 基站和扇区数据
  var cells = Map.data.cellList,
    length = cells.length
  
  if (zoom >= Map.const.cellZoom) {
    // 小区
    for (var i = 0; i < length; i++) {
      var cell = cells[i]
      var lon = cell.lon
      var lat = cell.lat
      var an = cell.an[0]
      var cellCount = cell.cellCount
      var maxRadius = cellCount * 20

      if (
        info.bounds.contains({
          lon: lon,
          lat: lat
        })
      ) {
        var dot = map.latLngToContainerPoint({
          lon: lon,
          lat: lat
        })
        var freqs = cell.f,
          freqsLength = freqs.length;

        for (var j = 0; j < freqsLength; j++) {
          Draw.sector({
            stage: stage,
            x: dot.x,
            y: dot.y,
            start: SectorAngle.start(an, 20),
            end: SectorAngle.end(an, 20),
            radius: maxRadius - 20 * j,
            fillStyle: fillStyleMap[freqs[j]],
            strokeStyle: 'rgb(136, 123, 39)',
            anticlock: true,
            event: undefined
          })
        }
      }
    }
  } else if (zoom <= Map.const.voronoiZoom) {

    for (var i = 0; i < length; i++) {
      var cell = cells[i]
      var lon = cell.lon
      var lat = cell.lat

      if (
        info.bounds.contains({
          lon: lon,
          lat: lat
        })
      ) {
        var dot = map.latLngToContainerPoint({
          lon: lon,
          lat: lat
        })

        // 基站
        Draw.imgCircle({
          stage: stage,
          x: dot.x,
          y: dot.y,
          img: imgCircle,
          imgWidth: 8,
          imgHeight: 8
        })
      }
    }
  }

  stage.update()
}
